//var baseUrl = "http://101.231.189.28:8680";
var baseUrl = "http://101.231.189.26:8680";
//var baseUrl = "http://gomoredev.natapp4.cc";

var util = {
	pageCount: 1,
	orderlists: '',
	goodslists: '',
	activityLists: []
}

$(function() {
	//退出操作
	$('.quit').click(function() {
		sessionStorage.clear();
		window.location.href = '../index.html';
	})
})

//日期格式化
Date.prototype.Format = function(fmt) {
	var o = {
		"M+": this.getMonth() + 1, //月份   
		"d+": this.getDate(), //日   
		"h+": this.getHours(), //小时   
		"m+": this.getMinutes(), //分   
		"s+": this.getSeconds(), //秒   
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度   
		"S": this.getMilliseconds() //毫秒   
	};
	if(/(y+)/.test(fmt))
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for(var k in o)
		if(new RegExp("(" + k + ")").test(fmt))
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}

//获取url中的参数
function getUrlParam(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
	var r = window.location.search.substr(1).match(reg); //匹配目标参数
	if(r != null) return unescape(r[2]);
	return null; //返回参数值
}

/**
 * 登录接口方法
 * 参数：用户名,密码
 * */
function login(postData) {
	$.ajax({
		url: baseUrl + "/palmmall-server/rest/authenticates/tenant-authen",
		cache: false,
		data: JSON.stringify(postData),
		dataType: 'json', //服务器返回json格式数据
		type: 'post', //HTTP请求类型
		contentType: "application/json",
		timeout: 10000, //超时时间设置为10秒；
		success: function(res) {
			//			console.log(res);
			if(res.success == true) {
				sessionStorage.setItem("userInfo", JSON.stringify(res.data));
				window.location.href = "html/main.html";
			} else {
				layer.msg(res.message);
			}
		},
		error: function(res) {
			layer.msg("网络出错……")
		}
	});
}

/**
 * 商品列表查询
 * */
function queryGoods(userInfo, page, keyword) {
	var def = $.Deferred();
	keyword = keyword || null;
	var postData = {
		"pageSize": 20,
		"page": page,
		"filter": {
			"contractUuid": userInfo.stores[0].contracts[0].uuid,
			"storeUuid": userInfo.stores[0].uuid,
			"keyword": keyword,
			"state": "using"
		}
	}
	$.ajax({
		url: baseUrl + "/palmmall-server/rest/sales/product/queryProducts",
		cache: false,
		data: JSON.stringify(postData),
		dataType: 'json', //服务器返回json格式数据
		type: 'post', //HTTP请求类型
		contentType: "application/json",
		timeout: 20000, //超时时间设置为10秒；
		success: function(res) {
			//			console.log(res);
			if(res.success == true) {
				sessionStorage.setItem("goodsList", JSON.stringify(res.data.records))
				util.pageCount = res.data.paging.pageCount; //记录总共的页数
				util.goodslists = res.data.records; //记录当前页商品
				$('#goods-list-box ul').empty(); //清空列表数据
				//循环输出展示商品列表
				for(var i = 0; i < res.data.records.length; i++) {
					if(!res.data.records[i].properties.model) {
						res.data.records[i].properties.model = '';
					}
					if(!res.data.records[i].price) {
						res.data.records[i].price = 0;
					}
					$('#goods-list-box ul').append('<li class="col-md-3 col-sm-3 col-xs-6">' +
						'<dl>' +
						'<dt><img class="img-responsive" src="../img/defaultImg.png"/></dt>' +
						'<dd>' +
						'<p>' + res.data.records[i].code + '&nbsp;' + res.data.records[i].name + '</p>' +
						'<p class="fc-gray">型号：<span>' + res.data.records[i].properties.model + '</span></p>' +
						'<div class="priceAndCart">' +
						'<span class="goodsPriceBox fc-red fl">' +
						'￥<span class="goodsPrice f20">' + res.data.records[i].price + '</span>' +
						'</span>' +
						'<button type="button" class="addToCart icon-shopping-cart bg-color-blue fr f20"></button>' +
						'</div>' +
						'</dd>' +
						'</dl>' +
						'</li>')
				}
				$('#goods-list-box ul li').each(function() {
					var index = $(this).index();
					var imgSrc = "../img/defaultImg.png";
					var self = this;
					if(res.data.records[index].fileIds[0]) {
						$.ajax({
							url: baseUrl + "/palmmall-server/rest/media/fileget/" + res.data.records[index].fileIds[0],
							cache: false,
							dataType: 'json', //服务器返回json格式数据
							type: 'get', //HTTP请求类型
							contentType: "application/json",
							timeout: 20000, //超时时间设置为10秒
							success: function(res) {
								if(res.success) {
									imgSrc = res.data;
									$(self).find('dl dt img').attr('src', imgSrc);
								} else {
									layer.msg(res.message)
								}
							},
							error: function(res) {
								console.log(res);
								layer.msg("网络出错……");
							}
						})
					}
				})
				def.resolve();

			} else {
				layer.msg(res.message);
			}
		},
		error: function(res) {
			console.log(res);
			layer.msg("网络出错……")
		}
	});

	return def.promise();
}

/**
 * 查询购物车图片
 * */
function getImg() {
	var goods = JSON.parse(sessionStorage.getItem("cartGoods")); //本地存储的加入购物车的商品信息
	//	console.log(goods)
	for(var i = 0; i < $('.goodsitemImg').length; i++) {
		//		console.log(goods[i].goodsItem.fileIds[0])
		if(goods[i].goodsItem.fileIds && goods[i].goodsItem.fileIds[0]) {
			$.ajax({
				url: baseUrl + "/palmmall-server/rest/media/fileget/" + goods[i].goodsItem.fileIds[0],
				cache: false,
				async: false, //设置成同步
				dataType: 'json', //服务器返回json格式数据
				type: 'get', //HTTP请求类型
				contentType: "application/json",
				timeout: 20000, //超时时间设置为10秒
				success: function(res) {
					if(res.success) {
						var index = i;
						var reg = new RegExp(goods[i].goodsItem.code);
						for(var j = 0; j < goods.length; j++) {
							if(reg.test($('.codeandname').eq(j).html())) { //便利当前购物车的商品，如果商品code相同，获取当前相同code的商品的索引
								index = j;
							}
						}
						$('.goodsitemImg').eq(index).attr('src', res.data);
					} else {
						layer.msg(res.message)
					}
				},
				error: function(res) {
					console.log(res);
					layer.msg("网络出错……");
				}
			})
		} else {
			$('.goodsitemImg').eq(i).attr('src', '../img/defaultImg.png');
		}
	}
}

/**
 * 生成订单
 * */
function generateOrder(postData, time, operId, operName) {
	$.ajax({
		url: baseUrl + "/palmmall-server/rest/moonstar/order/save?time=" + time + "&operator.operId=" + operId + "&operator.operName=" + operName,
		//		url: baseUrl + "/palmmall-server/rest/moonstar/order/save",
		cache: false,
		//		async: true,
		data: JSON.stringify(postData),
		dataType: 'json', //服务器返回json格式数据
		type: 'post', //HTTP请求类型
		contentType: "application/json;charset=utf-8",
		//		timeout: 10000, //超时时间设置为10秒
		success: function(res) {
			//			console.log(res);
			if(res.success == true) {
				sessionStorage.removeItem('cartGoods'); //清除本地购物车信息
				sessionStorage.removeItem('rateInfo'); //清除折扣率缓存
				sessionStorage.removeItem('upload'); //清除上传图片信息
				sessionStorage.removeItem('newAddress'); //清除新增地址
				sessionStorage.removeItem('returnFileIds'); //清除上传图片返回id本地存储
				sessionStorage.removeItem('editOrderUuid'); //清楚修改订单返回的uuid
				sessionStorage.removeItem('version'); //清楚修改订单返回的version
				setTimeout(function() {
					layer.closeAll('loading');
					window.location.href = "myOrders.html";
				}, 100)
			} else {
				layer.closeAll('loading');
				layer.msg(res.message);
			}
		},
		error: function(res) {
			layer.closeAll('loading');
			console.log(res);
			layer.msg("网络出错……")
		}
	});
}

/**
 * 查询订单
 * */
function queryOrders(userInfo, page) {
	var postData = {
		pageSize: 20,
		page: page,
		filter: {
			contracts: [userInfo.stores[0].contracts[0].uuid],
			storeUuid: userInfo.stores[0].uuid
		}
	}
	$.ajax({
		url: baseUrl + "/palmmall-server/rest/moonstar/order/query",
		cache: false,
		data: JSON.stringify(postData),
		dataType: 'json', //服务器返回json格式数据
		type: 'post', //HTTP请求类型
		contentType: "application/json",
		timeout: 10000, //超时时间设置为10秒；
		success: function(res) {
			//			console.log(res);
			if(res.success == true) {
				sessionStorage.setItem("myorders", JSON.stringify(res.data));
				util.orderlists = res.data.records; //将订单列表赋值
				util.pageCount = res.data.paging.pageCount;
				$('#ordersListsMain').empty(); //清空数据列表
				for(var i = 0; i < res.data.records.length; i++) {
					var color = "fc-green";
					var colorbg = "bg-color-qing";
					var showOrHide = ''; //控制作废订单显示隐藏
					if(res.data.records[i].bizState == "ineffect") {
						res.data.records[i].bizState = "未生效";
						color = "fc-qinglan";
						colorbg = "bg-color-qing";
						showOrHide = "show";
					} else if(res.data.records[i].bizState == "aborted") {
						res.data.records[i].bizState = "已作废";
						color = "fc-black";
						colorbg = "bg-color-gray"; //颜色灰色
						showOrHide = "hide"; //隐藏作废按钮
					} else if((res.data.records[i].bizState == "receipted")) {
						res.data.records[i].bizState = "已收款";
						color = "fc-darkgreen";
						colorbg = "bg-color-qing";
						showOrHide = "hide";
					} else if((res.data.records[i].bizState == "receipting")) {
						res.data.records[i].bizState = "部分收款";
						color = "fc-qinglan";
						colorbg = "bg-color-qing";
						showOrHide = "hide";
					} else if((res.data.records[i].bizState == "declaration")) {
						res.data.records[i].bizState = "已报单";
						color = "fc-qinglan";
						colorbg = "bg-color-qing";
						showOrHide = "hide";
					} else if((res.data.records[i].bizState == "passed")) {
						res.data.records[i].bizState = "已通过";
						color = "fc-qinglan";
						colorbg = "bg-color-qing";
						showOrHide = "hide";
					} else if((res.data.records[i].bizState == "rejected")) {
						res.data.records[i].bizState = "已驳回";
						color = "fc-qinglan";
						colorbg = "bg-color-qing";
						showOrHide = "hide";
					}
					if(res.data.records[i].deliveryMode == "delivery") {
						res.data.records[i].deliveryMode = "送货";
					} else if(res.data.records[i].deliveryMode == "selfExtract") {
						res.data.records[i].deliveryMode = "自提";
					} else {
						res.data.records[i].deliveryMode = "货运";
					}
					if(res.data.records[i].install == true) {
						res.data.records[i].install = "是";
					} else {
						res.data.records[i].install = "否";
					}
					var imgSrc = '../img/defaultImg.png';

					$('#ordersListsMain').append('<div class="ordersListsItem">' +
						'<div class="listsItemHead ' + colorbg + '">' +
						'<span>' + res.data.records[i].orderDate + '</span><span style="margin-left: 30px;">订单号：' + res.data.records[i].billNumber + '</span><span class="' + color + ' f18 fr">' + res.data.records[i].bizState + '</span>' +
						'</div>' +
						'<ul class="listsItem">' +
						'<li class="col-md-3 col-sm-3 col-xs-3 text-center ordersItem">' +
						'<dl class="center-block">' +
						'<dt class="fl"><img class="goodsimg" src="' + imgSrc + '"/></dt>' +
						'<dd class="fl text-left">' +
						'<p>' + res.data.records[i].customerName + '</p>' +
						'</dd>' +
						'</dl>' +
						'</li>' +
						'<li class="col-md-2 col-sm-2 col-xs-2 text-center">' + res.data.records[i].customerTelephone + '</li>' +
						'<li class="col-md-2 col-sm-2 col-xs-2 text-center">' +
						'<span>' + res.data.records[i].appointmentDeliveryDate.split(" ")[0] + '</span>' +
						'</li>' +
						'<li class="col-md-1 col-sm-1 col-xs-1 text-center"><span>' + res.data.records[i].stdTotal + '</span></li>' +
						'<li class="col-md-1 col-sm-1 col-xs-1 text-center">' + res.data.records[i].install + '</li>' +
						'<li class="col-md-1 col-sm-1 col-xs-1 text-center">' + res.data.records[i].deliveryMode + '</li>' +
						'<li class="col-md-2 col-sm-2 col-xs-2 text-center">' +
						'<button class="bg-color-blue cancelledOrder ' + showOrHide + '">作废订单</button>' +
						'<button class="seeDetails bg-color-blue seemore">查看详情</button>' +
						'</li>' +
						'</ul>' +
						'</div>')
				}
			} else {
				layer.msg(res.message);
			}
		},
		error: function(res) {
			layer.msg("网络出错……")
		}
	});
}
/**
 * 获取我的订单图片
 * */
function getOrderImg() {
	if(res.data.records[i].fileIds != null) {
		$.ajax({
			url: baseUrl + "/palmmall-server/rest/media/fileget/" + res.data.records[i].fileIds[0],
			cache: false,
			dataType: 'json', //服务器返回json格式数据
			type: 'get', //HTTP请求类型
			contentType: "application/json",
			timeout: 20000, //超时时间设置为10秒
			success: function(res) {
				//console.log(res)
				if(res.success) {
					imgSrc = res.data;
				} else {
					layer.msg(res.message)
				}
			},
			error: function(res) {
				console.log(res);
				layer.msg("网络出错……");
			}
		})
	}
}
/**
 * 获取订单详情
 * */
function getOrderDetails(id) {
	$.ajax({
		url: baseUrl + "/palmmall-server/rest/moonstar/order/" + id,
		cache: false,
		//		data: JSON.stringify(postData),
		dataType: 'json', //服务器返回json格式数据
		type: 'get', //HTTP请求类型
		contentType: "application/json",
		timeout: 10000, //超时时间设置为10秒；
		success: function(res) {
			//			console.log(res);
			if(res.success == true) {
				sessionStorage.setItem("orderItemDetails", JSON.stringify(res.data));
				setTimeout(function() {
					window.location.href = "../html/orderDetail.html"
				}, 100);
			} else {
				layer.msg(res.message);
			}
		},
		error: function(res) {
			layer.msg("网络出错……")
		}
	});
}

/**
 * 作废订单
 * */
function cancelledOrder(uuid, version, time, operId, operName) {
	$.ajax({
		url: baseUrl + "/palmmall-server/rest/moonstar/order/abort?id=" + uuid + "&version=" + version + "&time=" + time + "&operator.operId=" + operId + "&operator.operName=" + operName,
		//		url: baseUrl + "/palmmall-server/rest/moonstar/order/abort?id=" + uuid,
		cache: false,
		dataType: 'json', //服务器返回json格式数据
		type: 'put', //HTTP请求类型
		contentType: "application/json",
		timeout: 10000, //超时时间设置为10秒；
		success: function(res) {
			//			console.log(res);
			if(res.success == true) {
				layer.msg("已作废订单");
				setTimeout(function() {
					window.location.reload();
				}, 100)
			} else {
				layer.msg(res.message);
			}
		},
		error: function(res) {
			console.log(res);
			layer.msg("网络出错……")
		}
	});
}

/**
 * 查询促销活动
 * */
function queryActivity(postData, newAddress, preAcitivity) {
	$.ajax({
		url: baseUrl + "/palmmall-server/rest/esc/prom/query",
		cache: false,
		dataType: 'json', //服务器返回json格式数据
		data: JSON.stringify(postData),
		type: 'post', //HTTP请求类型
		contentType: "application/json",
		timeout: 10000, //超时时间设置为10秒；
		success: function(res) {
			//			console.log(res);
			if(res.success == true) {
				//				util.activityLists = res.data; //将获取到的活动详情数据赋值存储
				util.activityLists = [];
				if(res.data.amountActivities && res.data.amountActivities.length > 0) {
					for(var i = 0; i < res.data.amountActivities.length; i++) {
						util.activityLists.push(res.data.amountActivities[i]);
					}
				}
				if(res.data.giftActivies && res.data.giftActivies.length > 0) {
					for(var i = 0; i < res.data.giftActivies.length; i++) {
						util.activityLists.push(res.data.giftActivies[i]);
					}
				}
				console.log(util.activityLists)

				$('.activityBox ul').empty();
				for(var i = 0; i < util.activityLists.length; i++) {
					$('.activityBox ul').append('<li><input class="activityItem" type="checkbox" name="act" />' + util.activityLists[i].activityName + '</li>')
				}
				if(newAddress && $.isArray(newAddress.preActivities)) {
					if(newAddress.preActivities.length > 0) {
						for(var i = 0; i < util.activityLists.length; i++) {
							for(var j = 0; j < newAddress.preActivities.length; j++) {
								//如果已经存在的收获信息中的活动的id和获取到的活动id相等，说明选择了这个活动，让这个活动为选中状态
								if(newAddress.preActivities[j].activityName == util.activityLists[i].activityName) {
									$('.activityItem').eq(i).prop('checked', true);
								}
							}
						}
					}
				}
				if(preAcitivity && $.isArray(preAcitivity)) { //如果是初次进入页面，没有newAddress数据，但是用户已经操作过预约活动
					if(preAcitivity.length > 0) {
						for(var i = 0; i < util.activityLists.length; i++) {
							for(var j = 0; j < preAcitivity.length; j++) {
								if(preAcitivity[j].activityName == util.activityLists[i].activityName) {
									$('.activityItem').eq(i).prop('checked', true);
								}
							}
						}
					}
				}
			} else {
				layer.msg(res.message);
			}
		},
		error: function(res) {
			layer.msg("网络出错……")
		}
	});
}